<template>
  <div style="min-height: 500px">
    <h2>管理项目组 -- {{groupName}}</h2>

    <div style="margin: 20px auto;">
      <h3>成员管理</h3>
      <el-table
        :data="members"
        border
        style="width: 100%">
        <el-table-column
          align="center"
          prop="userName"
          width="100"
          label="姓名">
        </el-table-column>
        <el-table-column
          align="center"
          prop="userGrade"
          width="80"
          label="年级">
        </el-table-column>
        <el-table-column
          align="center"
          prop="joinTime"
          width="150"
          label="加入时间">
        </el-table-column>
        <el-table-column
          align="center"
          width="120"
          label="权限">
          <template scope="scope">
            <el-tag v-show="!members[scope.$index].isAdmin">用户</el-tag>
            <el-tag v-show="!groupInfo.owner.id===userInfo.id && members[scope.$index].isAdmin" type="primary">管理员
            </el-tag>
            <el-tag v-show="groupInfo.owner.id===userInfo.id" type="success">拥有者</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="要求提交"
          width="120">
          <template scope="scope">
            <el-checkbox v-model="members[scope.$index].needSubmit"
                         @change="handleUpdateNeedSubmit(scope.$index)"></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="操作">
          <template scope="scope">
            <!-- 项目拥有者 + 用户不是管理员 -->
            <el-button v-show="groupInfo.owner.id===userInfo.id
            && !members[scope.$index].isAdmin
            && !members[scope.$index].id===userInfo.id"
                       @click="handleRemoveAdmin(scope.$index, scope.row)"
                       type="text" size="small">设为管理员
            </el-button>
            <!-- 项目拥有者 + 用户是管理员 -->
            <el-button
              v-show="
              groupInfo.owner.id===userInfo.id
              && members[scope.$index].isAdmin
              && !members[scope.$index].id===userInfo.id"
              @click="handleSetAdmin(scope.$index, scope.row)"
              type="text" size="small">取消管理员
            </el-button>
            <!-- ( 项目管理员 + 用户不是管理员 ) 或 ( 项目拥有者 + 用户是管理员 )-->
            <el-button
              v-show="
              (groupInfo.owner.id===userInfo.id
              || !members[scope.$index].isAdmin)
              && !members[scope.$index].id===userInfo.id"
              @click="handleRemove(scope.$index, scope.row)"
              type="danger" size="small">移出
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加成员按钮 -->
    <div class="div-margin20">
      <el-button type="primary" @click="handleAddMember">添加成员</el-button>
    </div>

    <div class="grayBoundTop20">
      <h3>模板管理</h3>
      <div id="editor" style="padding-left: 5px;padding-right: 5px">
        <mavon-editor
          v-model="markdown_value"
          default_open="edit"
          :subfield="false"
          :toolbars="toolbars"
          style="height: 100%"></mavon-editor>
        <!-- 更新模板按钮 -->
        <div class="div-margin20 div-right">
          <el-button type="primary" @click="handleUpdateTemplate">更新</el-button>
        </div>
      </div>
    </div>

    <!-- 对话框 -->
    <el-dialog title="添加成员" :visible.sync="dialogFormVisible">
      <el-form>
        <el-form-item label="邮箱" label-width="200">
          <el-input v-model="queryEmail" auto-complete="off" @change="search"></el-input>
          <p v-show="queryItem.name">姓名：{{queryItem.name}} 年级：{{queryItem.grade}}</p>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="search" :disabled="!queryEmail">搜 索</el-button>
        <el-button @click="cancelAdd">取 消</el-button>
        <el-button type="primary" @click="confirmAdd" :disabled="!enableToAdd">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import * as api_group from '../../api/group';
  import * as api_user from '../../api/user';
  import {Table, TableColumn, Button, Form, FormItem, Dialog, Input, Tag, Checkbox} from 'element-ui'
  import * as $ from '../../utils/HHUtil';
  import {mapGetters} from 'vuex';
  import {mavonEditor} from 'mavon-editor'
  import 'mavon-editor/dist/css/index.css'

  export default {
    props: {},
    components: {
      mavonEditor,
      'el-table': Table,
      'el-table-column': TableColumn,
      'el-button': Button,
      'el-form': Form,
      'el-form-item': FormItem,
      'el-tag': Tag,
      'el-dialog': Dialog,
      'el-input': Input,
      'el-checkbox': Checkbox,
    },
    computed: {
      ...mapGetters(['userInfo'])
    },
    data() {
      return {
        groupName: '华为',
        members: [],
        groupId: 0,
        groupInfo: {},
        queryEmail: '',
        dialogFormVisible: false,
        queryItem: {},
        enableToAdd: false,
        markdown_value: '',
        toolbars: {
          bold: true, // 粗体
          italic: true, // 斜体
          header: true, // 标题
          underline: true, // 下划线
          strikethrough: true, // 中划线
          mark: true, // 标记
          superscript: true, // 上角标
          subscript: true, // 下角标
          quote: true, // 引用
          ol: true, // 有序列表
          ul: true, // 无序列表
          link: true, // 链接
          imagelink: false, // 图片链接
          code: true, // code
          table: true, // 表格
          fullscreen: true, // 全屏编辑
          readmodel: true, // 沉浸式阅读
          htmlcode: true, // 展示html源码
          help: true, // 帮助
          /* 1.3.5 */
          undo: true, // 上一步
          redo: true, // 下一步
          trash: true, // 清空
          save: true, // 保存（触发events中的save事件）
          /* 1.4.2 */
          navigation: true, // 导航目录
          /* 2.1.8 */
          alignleft: true, // 左对齐
          aligncenter: true, // 居中
          alignright: true, // 右对齐
          /* 2.2.1 */
          subfield: true, // 单双栏模式
          preview: true, // 预览
        }
      }
    },
    methods: {
      handleRemove(index, row) {
        let form = {
          userId: this.members[index].userId,
          groupId: this.groupId
        };
        api_group.removeMember(form).then(() => {
          this.refresh();
        }).catch((err) => {
          this.$message.error("移除失败：" + err.errmsg);
        });
      },
      handleSetAdmin(index, row) {
        let form = {
          userId: this.members[index].userId,
          groupId: this.groupId,
          isAdmin: false
        };
        api_group.setAsAdmin(form).then(() => {
          this.refresh();
        }).catch((err) => {
          this.$message.error("设置管理员操作失败：" + err.errmsg);
        });
      },
      handleRemoveAdmin(index, row) {
        let form = {
          userId: this.members[index].userId,
          groupId: this.groupId,
          isAdmin: false
        };
        api_group.setAsAdmin(form).then(() => {
          this.refresh();
        }).catch((err) => {
          this.$message.error("取消管理员操作失败：" + err.errmsg);
        });
      },
      updateGroupMemberInfo() {
        api_group.getMembers({'id': this.groupId}).then((data) => {
          this.members = data.body;
        }).catch((err) => {
          this.$message.error('刷新数据失败：' + err.errmsg);
        })
      },
      search() {
        api_user.queryByEmail({email: this.queryEmail}).then((data) => {
          this.queryItem = data;
          this.enableToAdd = true;
        }).catch((err) => {
          this.queryItem = '';
        })
      },
      cancelAdd() {
        this.queryEmail = '';
        this.dialogFormVisible = false;
        this.queryItem = {};
        this.enableToAdd = false;
      },
      confirmAdd() {
        let form = new FormData();
        form.append("userId", this.queryItem.id);
        form.append("groupId", this.groupId);
        api_group.addMember(form).then(() => {
          this.refresh();
          this.queryEmail = '';
          this.dialogFormVisible = false;
          this.queryItem = {};
          this.enableToAdd = false;
          this.$message.success('组员已经添加！');
        }).catch((err) => {
          this.$message.error('添加失败：' + err.errmsg);
        });
      },
      handleAddMember() {
        this.dialogFormVisible = !this.dialogFormVisible;
      },
      resetTemplate() {
        this.markdown_value = this.groupInfo.postTemplate;
      },
      getGroupInfo() {
        api_group.getGroupInfo({id: this.groupId}).then((data) => {
          this.groupInfo = data;
          this.resetTemplate();
        }).catch((err) => {
          this.$message.error('获取项目信息失败：' + err.errmsg);
        })
      },
      handleUpdateTemplate() {
        let form = new FormData();
        form.append('id', this.groupId);
        form.append('template', this.markdown_value);
        api_group.setPostTemplate(form).then(() => {
          this.$message.success('模板已经更新!');
          this.getGroupInfo();
        }).catch(err => {
          this.$message.error('模板更新失败: ' + err.errmsg);
        })
      },
      handleUpdateNeedSubmit(index) {
        let form = new FormData();
        form.append('groupId', this.groupId);
        form.append('userId', this.members[index].userId);
        form.append('needSubmit', this.members[index].needSubmit);
        api_group.setNeedSubmit(form).catch(err => {
          this.$message.error('更新失败: ' + err.errmsg);
          this.members[index].needSubmit = !this.members[index].needSubmit;
        })
      },
      refresh() {
        this.updateGroupMemberInfo();
        this.getGroupInfo();
      }
    },
    created() {
      let params = this.$route.params;
      this.groupId = params.groupId;
      this.queryItem = {};
      this.enableToAdd = false;
      this.refresh();
    },
    mounted() {
      let params = this.$route.params;
      this.groupId = params.groupId;
      this.queryItem = {};
      this.enableToAdd = false;
      this.refresh();
    }
  };
</script>

<style>

</style>
